<?php

namespace app\index\service;

use app\admin\service\PersonnelService;
use app\common\model\Member;
use app\index\dao\MemberDao;
use app\index\traits\SessionAfterLocationTrait;
use app\index\traits\SessionTrait;
use ShidianUtil\Captcha\Captcha;
use think\exception\ValidateException;

/**
 * 测试账号登录
 * Class SessionTestService
 * @package app\index\service
 */
class SessionTestService
{
    use SessionTrait;
    use SessionAfterLocationTrait;

    private MemberService $memberService;
    private MemberDao $memberDao;
    private Captcha $captcha;

    public function __construct(MemberService $memberService, MemberDao $memberDao, Captcha $captcha)
    {
        $this->memberService = $memberService;
        $this->memberDao = $memberDao;
        $this->captcha = $captcha;
    }

    /**
     * 测试账号登录
     * @param $params
     * @return Member
     */
    public function login($params, $data): Member
    {
        $member = Member::where('phone', $params['phone'])->find();

        if (!$member) {
            throw new ValidateException('该用户不存在');
        }

        if (isset($data['openidWeiXin']) || isset($data['unionid'])) {
            $member->openidWeiXin = $data['openidWeiXin'] ?? '';
            $member->unionid = $data['unionid'] ?? '';
            $member->save();
        }

        if (isset($data['openidDouyin']) || isset($params['unionidDouyin'])) {
            $member->openidDouyin = $data['openidDouyin'] ?? '';
            $member->unionidDouyin = $data['unionidDouyin'] ?? '';
            $member->save();
        }

        // 查询前端用户信息
        $member = $this->memberDao->findByLogin($member->id);

        // **************** 登录并返回 ****************

        // 设置定位
        $this->setLocation($member);

        // 刷新token令牌
        $token = $this->getMemberTokenService()->add($member->id, 0, 30);

        // 给前端的参数，包装一下
        $this->wrapToken($member, $token);

        return $member;
    }

    private function getMemberTokenService(): MemberTokenService
    {
        return app(MemberTokenService::class);
    }

    private function getPersonnelService(): PersonnelService
    {
        return app(PersonnelService::class);
    }
}
